import axios from 'axios'
import qs from 'qs'
import store from '../store/store'
import router from '../router/router'

const http = axios.create({
  baseURL: process.env.NODE_ENV == 'development' ? process.env.VUE_APP_API : process.env.VUE_APP_API,
  timeout: 30000
})

// 拦截器  请求之前做点啥
http.interceptors.request.use(
  config => {
    // 判断store是否有token 有就加入请求头
    const token = store.state.token
    if (token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 返回的时候拦截一下
http.interceptors.response.use(
  res => {
    if (res.data.code == 200) {
      res.data.status = 1
    } else {
      res.data.status = 0
    }
    switch (res.data.code) {
      case 403:
        router.push('/')
        break
      case 404:
        router.push('/')
        break
    }
    return res.data
  },
  error => {
    // 异常返回 根据相应的状态码进行对应操作
    if (error.response) {
      error.response.data.status = 0
      switch (error.response.status) {
        case 403:
          store.dispatch('userLogout') // 可能是token过期，清除它
          window.location.href = '/'
          break
        case 401:
          store.dispatch('userLogout') // 可能是token过期，清除它
          window.location.href = '/'
          break
        default:
          return error.response.data
      }
    }
  }
)
export const sysLogin = (params: object) => {
  return http.post('/sys/login', qs.stringify(params))
}

export const sysRegistry = (params: object) => {
  return http.post('/sys/registry', qs.stringify(params))
}

// 获取个人信息
export const sysGetInfo = (params: object) => {
  return http.get('/sys/get_info', { params })
}

// 获取所有公司
export const getAllCompany = (params: object) => {
  return http.get('/company/get_all_list', { params })
}

// 编辑公司的信息
export const sysEditCompany = (params: object) => {
  return http.post('/sys/edit_company', qs.stringify(params))
}

// 编辑公司的信息
export const sysEditMyInfo = (params: object) => {
  return http.post('/sys/edit_my_info', qs.stringify(params))
}

// 编辑公司的信息
export const sysEditUserInfo = (params: object) => {
  return http.post('/sys/edit_user_info', qs.stringify(params))
}

// 获取七牛token
export const qiniuGetToken = () => {
  return http.get('/qiniu/get_token')
}
